package com.mornd.gulimall.common.config;

import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.mornd.gulimall.common.core.result.AjaxResult;
import com.mornd.gulimall.common.core.utils.RespUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: mornd
 * @dateTime: 2023/8/31 - 7:30
 */

@Slf4j
@Configuration
@ConditionalOnClass(SentinelAutoConfiguration.class)
public class SentinelConfig {

    @Bean
    public BlockExceptionHandler blockExceptionHandler() {
        return new BlockExceptionHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
                log.error(e.getRule().toString());
                AjaxResult r = AjaxResult.error(HttpStatus.TOO_MANY_REQUESTS.value(),
                        "当前访问人数过多");
                RespUtil.writeUtf8JSON(response, r);
            }
        };
    }
}
